<template>
    <el-row  >
        <el-col :lg='{span:20,offset:2}'>
            <!-- 企业信息 -->
            <el-tabs  v-model="activetab_com">
                  <el-tab-pane label="企业信息" name="com_info"></el-tab-pane>
            </el-tabs>
            <el-row>
                <el-col  :sm='16' :md='16' :lg='14'>
                    <el-form  label-width="180px" :label-position="labelPosition" align='left' size='small'  ref="form" :model='form' :rules='rules' >
                        <el-form-item label="企业名称："        prop='entName'>
                            <el-input v-model.trim="form.entName" placeholder='请输入企业名称'></el-input>
                        </el-form-item>
                        <el-form-item label="统一社会信用代码：" prop='creditCode'>
                            <el-input v-model.trim="form.creditCode"  placeholder='请输入统一社会信用代码'></el-input>
                        </el-form-item>
                        <el-form-item label="注册资金："  > 
                            <el-input v-model.trim="form.regCapital" type='number' placeholder='请输入注册资金'  class='number_right'><template slot="suffix">万元</template></el-input>
                        </el-form-item>
                        <el-form-item label="注册地址：">
                            <el-input v-model.trim="form.regAddr"  placeholder='请输入注册地址'></el-input>
                        </el-form-item>
                        <el-form-item label="法人名称：">
                            <el-input v-model.trim="form.legalPersonName"  placeholder='请输入法人名称'></el-input>
                        </el-form-item>
                        <el-form-item label="法人身份证号码：" prop='legalPersonIdc'>
                            <el-input v-model.trim="form.legalPersonIdc"  placeholder='请输入法人身份证号码'></el-input>
                        </el-form-item>
                        <el-form-item label="税务信息：" class='mb10'>
                            <el-input v-model.trim="form.taxTitle"  placeholder='抬头'></el-input>
                        </el-form-item>
                        <el-form-item >
                            <el-input v-model.trim="form.taxNo"  placeholder='税号'></el-input>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            <!-- 基本信息 &  银行账户 & 企业文件-->
            <el-tabs type="card" v-model='activetab_other'>
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name='basic_info'>
                    <el-form  label-width="180px"  :label-position="labelPosition" align='left' size='small'  ref='baseForm' :model='baseForm'  >
                        <el-form-item label="会员类型：">
                            <el-checkbox-group v-model="baseForm.checkList">
                                <el-checkbox label="1"  value='1'>交易类会员 </el-checkbox>
                                <el-checkbox label="2"  value='2'>服务类会员 </el-checkbox>
                                <el-checkbox label="3"  value='3'>经济类会员 </el-checkbox>
                                <el-checkbox label="4"  value='4'>承销类会员 </el-checkbox>
                                <el-checkbox label="5"  value='5'>综合类会员 </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                        <el-form-item label="企业联系人：">
                            <el-button type="primary" icon="el-icon-plus" size="small" round @click="addDomain">新增</el-button>
                        </el-form-item>
                        <el-form-item  
                            v-for="(domain, index) in baseForm.connect"
                            :label="'联系人' + (index+1) + '：'"
                            :key="index"
                            >
                            <el-input v-model="domain.contactName" placeholder='请输入姓名'  class='com_connect mr8'></el-input>
                            <el-input v-model="domain.position" placeholder='请输入职务' class='com_connect mr8'></el-input>
                            <el-input v-model="domain.phone" placeholder='请输入手机号' class='com_connect mr8'></el-input>
                            <el-input v-model="domain.email" placeholder='请输入邮箱' class='com_connect '></el-input>
                            <el-button type="danger"  size="mini" round @click.prevent="removeDomain(index)"  v-if='baseForm.connect.length!="1"'>删除</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <!-- 银行账户 -->
                <el-tab-pane label="银行账户" name='bank_info'>
                    <el-form  label-width="220px" align='left' size='small' >
                        <el-button type="primary" icon="el-icon-plus" size="small" round @click="addBankCount"  class='mb16'>新增</el-button>
                        <el-table
                          :data="bankList"
                          header-row-class-name='bankheader' 
                          style="width: 100%">
                            <el-table-column label="账户列表">
                                <el-table-column  prop="accountName" label="账户名称"  align='center'></el-table-column>
                                <el-table-column  prop='subbranchName' label="支行名称" align='center'></el-table-column>
                                <el-table-column  prop='bankAccount' label="银行账号" align='center'></el-table-column>
                                <el-table-column   label="操作" align='center'>
                                    <template v-slot="list">
                                        <el-button  type="primary" size="mini" round @click="bankEdit(list.$index, list.row)">编辑</el-button>
                                        <el-button  type="danger"  size="mini" round @click="bankDelete(list.$index, list.row)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table-column>
                        </el-table>
                    </el-form>
                </el-tab-pane>
                <!-- 企业文件 -->
                <el-tab-pane label="企业文件" name='file_info'>
                    <el-form  label-width="220px" align='left' size='small'  >
                        <el-button type="primary" icon="el-icon-plus" size="small" round  @click="addFiles"  class='mb16'>新增</el-button>
                        <el-tabs v-model="activetab_file"   class='ml10'>
                            <el-tab-pane label="文件列表" name='file_current' >
                                <el-table
                                    :data="filelist"
                                    header-row-class-name='bankheader' 
                                    style="width: 100%">
                                    <el-table-column  prop="fileName" label="文件名称"  align='center'></el-table-column>
                                    <el-table-column   label="操作" align='center'>
                                        <template v-slot="list">
                                            <el-button  type="primary" size="mini" round @click="downloadFile(list.row.fileCode)">下载</el-button>
                                            <el-button  type="danger"  size="mini" round @click="fileDelete( list.row.code)">删除</el-button>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-tab-pane>
                        </el-tabs>
                    </el-form>
                </el-tab-pane>
            </el-tabs>
            <div  class="mt12 mb20  text-center">
                <el-button @click="common_goback()">取 消</el-button>
                <el-button type="primary" @click="submit('form')"  :loading='displayLoading' >确 定</el-button>
            </div>
        </el-col>
        <!-- 新增 银行账户 -->
        <BankCountEdit ref='addBank'  v-on:save-finished='bankAdd(arguments)'> </BankCountEdit>
        <!-- 新增 文件 -->
        <FileEdit ref='addFile'  v-on:save='recept(arguments)'> </FileEdit>
    </el-row>
</template>

<script>
/*interface*/
import { submitAddCompany , ModifyCompany, DetailCompany, checkname  } from '@/api/company/index'
/*compnents*/
import BankCountEdit  from '@/components/company/bankCount'
import FileEdit  from '@/components/common/FileEdit'
export default {
    name: 'addNew',
    data () {
        return {
            /*static*/
            //tab active 值
            activetab_com:'com_info',
            activetab_other:'basic_info',
            activetab_file:'file_current',
            /*pc或移动端 label对齐方式*/
            labelPosition:'right',

            /*active*/
            displayLoading: false,//确定提交按钮等待加载状态
            //1.企业信息form
            form:{
                entName:'', //企业名
                creditCode:'',   //社会代码
                regCapital:'',
                regAddr:'',
                legalPersonName:'',
                legalPersonIdc:'',
                taxTitle:'',
                taxNo:'',
            },
            //2.基本信息
            baseForm:{
                checkList: ['1'],//会员类型,默认选择交易类会员
                connect:[
                  {contactName:'',position:'',phone:'',email:''}
                ],
            },
            //3.银行账户列表
            bankList:[],
            //4.上传的文件列表 
            filelist:[],

            //form-rules
            rules:{
              entName:[
                  { required: true, message: '请输入企业名称', trigger: 'blur' },
                  { validator: this.checkEntName,  trigger: 'blur' }
              ],
              creditCode:[
                  { required: true, message: '请输入18位统一社会信用代码', trigger: 'blur' },
                  { validator: this.checkEntName,  trigger: 'change' }
              ],
              legalPersonIdc:[
                  { validator: this.checkIdentCode,  trigger: 'blur' }
              ]
            },
            
            isEdit:false,//是否为编辑状态 
            company_code:'',//编辑状态下获取的企业code
            comUserCode:'',//编辑状态下获取的企业usercode
            submitSuccess:false,//新增成功 编辑成功 =>清除缓存；取消编辑 返回上一页 =>仍然保持原页面
        }
    },
    created() {
        //网页宽度判断，更改布局
        let clientWidth = document.body.clientWidth
        if(clientWidth<600){
            this.labelPosition='top'
        }
        //初始化页面-确认是否编辑状态
        this.company_code = this.$route.query.code
        if(this.company_code){
            this.pageInit(this.company_code)
            this.isEdit = true //编辑状态
        }
    },
    methods:{
        /*编辑状态下 初始化 页面 S*/
        pageInit(code){
            let that =this
            DetailCompany(code).then(res => {
               if(res.data.flag == true){
                    //企业信息
                    let form_base = res.data.data.bizEnt
                    //账户信息
                    let bankList = res.data.data.bizEntBankList
                    //文件信息
                    let bizEntFileList = res.data.data.bizEntFileList
                    /*1.企业form*/
                    that.form = form_base
                    /*2.基本信息form  baseform与form不是同一个表单*/ 
                    //基本信息-会员类型，需要由字符串转成数组回填
                    that.baseForm.checkList=that.form.entMemberType.split(',');
                    //基本信息-企业联系人回填 
                    [that.baseForm.connect] = [res.data.data.bizEntContactList]
                    // 联系人为空：初始化设置
                    if(that.baseForm.connect.length==0){
                        that.baseForm.connect=[]
                        that.baseForm.connect.push({contactName:'',position:'',phone:'',email:''})
                    }

                    /*3.账户form*/
                    //账户信息回填 
                    that.bankList = bankList

                    /*4.文件form*/
                    //文件信息 回填
                    that.filelist = bizEntFileList

                    /*5.企业usercode*/
                    that.comUserCode = res.data.data.bizEntUserCode
               }
            })
            .catch(error => {
                that.outputError(error)
            })
        },
        /*编辑状态下 初始化 页面 E*/

        /*表单操作 submit & 异步验证企业名称 & 增删改操作 S*/
        submit(formName) {
            let that = this
            this.$refs[formName].validate(valid => {
                if(valid){
                    //表单处理
                    //1.基本信息-会员类型选择值  由数组转为字符串
                    this.form.entMemberType=this.baseForm.checkList.join(',')

                    //判断联系人最后一条数据有没有输入  没有输入就置为空 存入后台  为了查看和编辑时没有空数据
                    let last_in = this.baseForm.connect.length-1
                    if(this.baseForm.connect[last_in].contactName == '' && this.baseForm.connect[last_in].position == ''  &&  this.baseForm.connect[last_in].phone == ''  &&  this.baseForm.connect[last_in].email == ''){
                        this.baseForm.connect.splice(last_in,1)
                    }
                    /*判断注册资金是否为空字符串 */
                    this.form.regCapital = this.form.regCapital == '' ?  0:this.form.regCapital
                    
                    //处理后提提交表单
                    this.displayLoading = true
                    //编辑状态修改提交
                    if(this.isEdit == true){
                        ModifyCompany(this.company_code,this.form,this.baseForm,this.bankList,this.filelist,this.comUserCode).then(res => {
                            if(res.data.flag == true){
                                this.submitSuccess = true
                                this.$message({type:'success',message:res.data.msg})
                                this.$router.push({path:'/company'})
                            }
                            else{
                                setTimeout(function(){
                                    that.displayLoading = false
                                },500)
                            }
                        })
                        .catch(error => {
                            that.outputError(error)
                            setTimeout(function(){
                                that.displayLoading = false
                            },500)
                        })  
                    }
                    //add提交
                    else{
                        submitAddCompany(this.form,this.baseForm,this.bankList,this.filelist).then(res => {
                            if(res.data.flag == true){
                                this.submitSuccess = true
                                this.$message({type:'success',message:res.data.msg})
                                this.$router.push({path:'/company'})
                            }
                            else{
                                setTimeout(function(){
                                    that.displayLoading = false
                                },500)
                            }
                        })
                        .catch(error => {
                            that.outputError(error)
                            setTimeout(function(){
                                that.displayLoading = false
                            },500)  
                        })
                    }
                  }
                else {
                  return false;
                }
            });
        },

        //异步验证企业名称是否已经存在
        checkEntName(rule, value,  callback){
            let operation ;
            //新增状态
            if(this.isEdit == false){
                operation = 1
                checkname(operation,this.form.entName,this.form.creditCode).then(res=>{
                  if(res.data.flag == true){
                      callback()
                  }
                  else{
                      return callback(new Error(res.data.msg));
                  }
                })
                // callback()
            }
            //编辑状态
            else{
                operation = 2
                checkname(operation,this.form.entName,this.form.creditCode,this.company_code).then(res=>{
                    if(res.data.flag == true){
                        callback()
                    }
                    else{
                        return callback(new Error(res.data.msg));
                    }
                })
            }
        },

        //表单增删改操作
        //新增联系人
        addDomain() {
            let index = this.baseForm.connect.length-1
            if(this.baseForm.connect[index].contactName == '' && this.baseForm.connect[index].position == ''  &&  this.baseForm.connect[index].phone == ''  &&  this.baseForm.connect[index].email == ''){
                this.$message({type:'warning',message:'请先填入上一条联系人相关信息！'})
                return 
            }
            else{
                this.baseForm.connect.push({
                  contactName: '',  
                  position:'',
                  phone:'',
                  email:''
                });
            }
        },
        //删除联系人  前台删除，提交后才实现后台删除
        removeDomain(index) {
            this.common_del(index,this.baseForm.connect)
        },
        //添加企业银行账户
        addBankCount(){
            this.$refs.addBank.$emit('openDialog')
        },
        //编辑银行账户
        bankEdit(index,row){
            this.$refs.addBank.$emit('openEditDialog',row,index)
        },
        //新增银行成功
        bankAdd(arg){
            //编辑回填
            if(arg[1] != undefined){
                let ind= arg[1]
                this.bankList.splice(ind,1,arg[0])
            }
            //新增回填
            else{
                this.bankList.push(arg[0])
            }
        },
        //del 银行前台删除
        bankDelete(index,row){
            this.common_del(index,this.bankList)
        },
        //新增文件
        addFiles(){
            this.$refs.addFile.$emit('openDialog')
        },
        //接收已经上传的文件，并返回列表
        recept(arg){
            let  form = arg[0] 
            form.forEach((item,index)=>{
                this.filelist.push({fileName:item.name,fileCode:item.code})
            }) 
        },
        //删除文件（新增时删除） 前台删除，提交后才实现后台删除
        fileDelete(index,row){
            this.common_del(index,this.filelist)
        },
        /*表单操作 submit & 异步验证企业名称 & 增删改操作 E*/
      
    },
    components:{
        BankCountEdit,
        FileEdit
    },
    mounted(){
      this.$nextTick(function () {
          window.onresize = () => {
              // console.log(document.body.clientWidth)
              if(document.body.clientWidth<600){
                  this.labelPosition = 'top'
              }
              if(document.body.clientWidth>=600){
                  this.labelPosition = 'right'
              }
          };
        })
    },
    beforeRouteLeave(to,from,next){
        /*提交时不需缓存*/
        from.meta.modifyCacheRoute = this.submitSuccess == true ? true :false
        next()
    }
}
</script>


<style scoped>
.com_account{width: 60%;}
.com_connect{width: 21%; margin-top: 0;}


@media screen and (max-width: 1240px) {
    .com_account{width: 100%;}
    .com_connect{width: 33%;margin-top: 10px;}
}
</style>
